package com.andova.component.pic;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.DrawableRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;

/**
 * Created by Administrator on 2018-08-16.
 *
 * @author kzaxil
 * @since 0.0.2
 */
public class GlideDisplay implements IPicDisplay {
    private static GlideDisplay mDisplay;

    public static GlideDisplay get() {
        if (mDisplay == null) {
            synchronized (GlideDisplay.class) {
                if (mDisplay == null) mDisplay = new GlideDisplay();
            }
        }
        return mDisplay;
    }

    @Override
    public void displayImage(Object attachTarget, String url, ImageView imageView) {
        with(attachTarget)
                .load(url)
                .into(imageView);
    }

    @Override
    public void displayImage(Object attachTarget, String url, ImageView imageView, @DrawableRes int placeholder, @DrawableRes int error) {
        with(attachTarget)
                .load(url)
                .apply(new RequestOptions().placeholder(placeholder).error(error))
                .into(imageView);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void displayImage(Object attachTarget, Object url, IPicDisplayOption option) {
        if (!(option.option() instanceof RequestOptions)) return;
        if (option.target() instanceof Target) {
            with(attachTarget)
                    .load(url)
                    .apply((RequestOptions) option)
                    .into((Target) option.target());
        } else if (option.target() instanceof ImageView) {
            with(attachTarget)
                    .load(url)
                    .apply((RequestOptions) option)
                    .into((ImageView) option.target());
        }
    }

    private RequestManager with(Object attachTarget) {
        if (attachTarget instanceof FragmentActivity) {
            return Glide.with((FragmentActivity) attachTarget);
        } else if (attachTarget instanceof Activity) {
            return Glide.with((Activity) attachTarget);
        } else if (attachTarget instanceof Fragment) {
            return Glide.with((Fragment) attachTarget);
        } else if (attachTarget instanceof android.app.Fragment) {
            return Glide.with((android.app.Fragment) attachTarget);
        } else if (attachTarget instanceof Context) {
            return Glide.with((Context) attachTarget);
        } else if (attachTarget instanceof View) {
            return Glide.with((View) attachTarget);
        } else {
            throw new IllegalArgumentException("attach target error!");
        }
    }
}
